//
//  XHRTopicPictureView.m
//  BuDeJie
//
//  Created by haoran on 16/4/15.
//  Copyright © 2016年 xuhaoran. All rights reserved.
//

#import "XHRTopicPictureView.h"
#import "XHRTopicItem.h"
#import "XHRSeeBigPictureViewController.h"

@interface XHRTopicPictureView()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property (weak, nonatomic) IBOutlet UIImageView *gifView;

@property (weak, nonatomic) IBOutlet UIButton *seeBigPictureButton;



@end
@implementation XHRTopicPictureView


-(void)awakeFromNib{

    self.autoresizingMask = UIViewAutoresizingNone;
    self.imageView.userInteractionEnabled = YES;
    
    [self.imageView addGestureRecognizer: [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(seeBigPicture)]];

}
/**
 *  查看大图
 */
-(void)seeBigPicture{
    XHRSeeBigPictureViewController * vc = [[XHRSeeBigPictureViewController alloc]init];
    vc.topicItem = self.topicItem;
    [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
    
}



#pragma mark - set方法
-(void)setTopicItem:(XHRTopicItem *)topicItem{
    
    _topicItem = topicItem;
    
    /*
     if(磁盘缓存有大图)
     直接设置大图
     else if(判断网络为WiFi)
     下载大图
     else if(判断网络为蜂窝数据)
     下载小图
     else 
     设置占位图片
     */
    [self.imageView xhr_setImageWithOriginalImageURL:topicItem.image1 thumbnailImageURL:topicItem.image0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        // 如果图片下载失败
        if (image == nil)  return ;
        // 如果不是大图

        if (!topicItem.isBigPicture) return;
        
        // 开启图形上下文
        CGFloat imageW = topicItem.middleFrame.size.width;
        CGFloat imageH = topicItem.middleFrame.size.height;
        
        UIGraphicsBeginImageContext(CGSizeMake(imageW, imageH));
        
        // 绘图
        [image drawInRect:CGRectMake(0, 0, imageW, imageW * topicItem.height / topicItem.width )];
        
        // 获得图片
        self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        
        // 关闭上下文
        UIGraphicsEndImageContext();
    }];
    
    // 设置gif
    self.gifView.hidden = !topicItem.is_gif;
    
    // 设置显示大图按钮
    self.seeBigPictureButton.hidden = !topicItem.isBigPicture;
}



@end
